<!-- src/views/AdminCategoryManagement.vue -->
<template>
  <div class="admin-category-management-container" v-loading="loading">
    <el-page-header content="板块管理" style="margin-bottom: 20px;" />

    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      closable
      style="margin-bottom: 20px;"
    />

    <!-- 创建/编辑表单 -->
    <!-- *** 修改: 使用 hasLgtPermission 控制表单显示 *** -->
    <el-card class="form-card" v-if="showForm && hasLgtPermission">
      <!-- 表单内容保持不变 -->
      <template #header>
        <div class="card-header">
          <span>{{ isEditing ? '编辑板块' : '创建新板块' }}</span>
          <el-button @click="cancelForm" size="small">取消</el-button>
        </div>
      </template>
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
        @submit.prevent="submitCategory"
      >
        <!-- 表单项保持不变 -->
        <el-form-item label="板块名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入板块名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入板块描述"
          />
        </el-form-item>
        <el-form-item label="图标URL" prop="iconUrl">
          <el-input v-model="categoryForm.iconUrl" placeholder="请输入图标URL" />
        </el-form-item>
        <el-form-item label="排序权重" prop="sortOrder">
          <el-input-number v-model="categoryForm.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitCategory" :loading="saving">
            {{ isEditing ? '更新' : '创建' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- *** --- *** -->

    <!-- 板块列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>板块列表</span>
          <!-- *** 修改: 使用 hasLgtPermission 控制创建按钮显示 *** -->
          <el-button v-if="hasLgtPermission" type="primary" @click="showCreateForm">创建新板块</el-button>
          <!-- *** --- *** -->
        </div>
      </template>
      <el-table :data="categories" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="sortOrder" label="排序" width="100" />
        <!-- *** 修改: 使用 hasLgtPermission 控制操作列显示 *** -->
        <el-table-column label="操作" width="200" v-if="hasLgtPermission">
          <template #default="scope">
            <el-button size="small" @click="showEditForm(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="confirmDeleteCategory(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        <!-- *** --- *** -->
        <!-- 如果没有权限，可以显示一个提示列或者完全隐藏操作列 -->
        <el-table-column label="操作" width="200" v-else>
          <template #default>
            <span style="color: #999;">无权限操作</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted,computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import {
  getCategories,
  createCategory,
  updateCategory,
  deleteCategory
} from '@/services/categoryService';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

// --- 修改: 更新权限检查逻辑 ---
// 原来的 hasAdminPermission 检查的是 CATEGORY_MANAGE 权限
// 现在我们需要检查用户是否已认证并且用户名是 'lgt'
const hasLgtPermission = computed(() => {
  // 1. 检查用户是否已认证
  if (!authStore.isAuthenticated) {
    console.log('hasLgtPermission: User not authenticated');
    return false;
  }

  // 2. 检查 currentUser 对象是否存在
  if (!authStore.currentUser) {
    console.log('hasLgtPermission: currentUser is null or undefined');
    return false;
  }

  // 3. 检查用户名是否为 'lgt'
  const username = authStore.currentUser.username;
  console.log('Checking username for Lgt permission:', username); // 调试日志
  const isLgt = username === 'lgt';
  console.log('Is user "lgt"?', isLgt); // 调试日志

  return isLgt;
});

const loading = ref(false);
const saving = ref(false);
const errorMessage = ref('');
const showForm = ref(false);
const isEditing = ref(false);

const categories = ref([]);

const categoryFormRef = ref();
const categoryForm = reactive({
  id: null,
  name: '',
  description: '',
  iconUrl: '',
  sortOrder: 0
});

const categoryRules = {
  name: [
    { required: true, message: '请输入板块名称', trigger: 'blur' },
    { min: 1, max: 255, message: '名称长度为 1 到 255 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 512, message: '描述长度不能超过 512 个字符', trigger: 'blur' }
  ],
  iconUrl: [
    { max: 512, message: '图标URL长度不能超过 512 个字符', trigger: 'blur' }
  ]
};

// 获取所有板块列表
const fetchCategories = async () => {
  loading.value = true;
  errorMessage.value = '';
  try {
    const response = await getCategories();
    categories.value = response.data || [];
  } catch (error) {
    console.error('Failed to fetch categories:', error);
    errorMessage.value = error.response?.data?.message || '获取板块列表失败';
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 显示创建表单
const showCreateForm = () => {
  isEditing.value = false;
  resetForm();
  showForm.value = true;
};

// 显示编辑表单
const showEditForm = (category) => {
  isEditing.value = true;
  // 将 category 数据填充到表单
  Object.assign(categoryForm, category);
  showForm.value = true;
};

// 取消表单
const cancelForm = () => {
  showForm.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  categoryForm.id = null;
  categoryForm.name = '';
  categoryForm.description = '';
  categoryForm.iconUrl = '';
  categoryForm.sortOrder = 0;
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields();
  }
};

// 提交板块 (创建或更新)
const submitCategory = async () => {
  if (!categoryFormRef.value) return;
  await categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true;
      errorMessage.value = '';
      try {
        let response;
        if (isEditing.value) {
          // 更新板块
          response = await updateCategory(categoryForm.id, {
            name: categoryForm.name,
            description: categoryForm.description,
            iconUrl: categoryForm.iconUrl,
            sortOrder: categoryForm.sortOrder
          });
          ElMessage.success('板块更新成功');
        } else {
          // 创建板块
          response = await createCategory({
            name: categoryForm.name,
            description: categoryForm.description,
            iconUrl: categoryForm.iconUrl,
            sortOrder: categoryForm.sortOrder
          });
          ElMessage.success('板块创建成功');
        }
        console.log('Category operation result:', response.data);
        // 操作成功后，刷新列表并隐藏表单
        await fetchCategories();
        showForm.value = false;
      } catch (error) {
        console.error('Category operation failed:', error);
        errorMessage.value = error.response?.data?.message || '操作失败';
        ElMessage.error(errorMessage.value);
      } finally {
        saving.value = false;
      }
    } else {
      console.log('Category form validation failed!');
      return false;
    }
  });
};

// 确认删除板块
const confirmDeleteCategory = (category) => {
  ElMessageBox.confirm(
    `确定要删除板块 "${category.name}" 吗？此操作不可撤销。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteCategory(category.id);
      ElMessage.success('板块删除成功');
      // 删除成功后，刷新列表
      await fetchCategories();
    } catch (error) {
      console.error('Category deletion failed:', error);
      errorMessage.value = error.response?.data?.message || '删除失败';
      ElMessage.error(errorMessage.value);
    }
  }).catch(() => {
    // 用户取消删除
  });
};


// 组件挂载时获取数据
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.admin-category-management-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.form-card, .list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-weight: bold;
}
</style>
